<script src="../../../../vue.config.js"></script>
<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="采购订单号" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="purchase_order"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="采购人员" prop="orderBy">
          <el-input v-model="formData.orderName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="采购日期" prop="orderTime">
          <el-date-picker
            v-model="formData.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="供应商名称" class="clickChoose" prop="supplierName">
          <el-input v-model="formData.supplierName" placeholder="请选择" readonly />
          <a class="clickChoose_button" @click.prevent="choosePeople">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="总数量" prop="totalNumber">
          <el-input v-model="formData.totalNumber" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item v-if="!formData.isTaxTotalMoney" label="含税总金额" prop="taxTotalMoney">
          <el-input v-model="formData.taxTotalMoney" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item v-else label="含税总金额" prop="taxTotalMoney">
          <el-input v-model="formData.taxTotalMoney" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :summary-method="getSummaries"
          :show-summary="true"
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column
            type="selection"
            align="center"
            width="70"
            :selectable="tableSelectable"
          />
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="采购数量"
            fixed="right"
            :min-width="SETTINGS.settings_decimalDigits_length"
            prop="purchaseNumber"
          >
            <template slot-scope="scope">
              <span>{{ scope.row. purchaseNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="含税单价" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.taxPrice"
                :disabled="scope.row.status == '3'"
                placeholder="请输入"
                type="number"
                clearable
                @input="changeTaxPrice($event,scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="税率%" min-width="120" prop="taxRateCode">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.taxRateCode"
                :disabled="scope.row.status == '3'"
                clearable
                filterable
                placeholder="请选择"
                @change="changeTaxRateCode($event,scope.row,scope.$index)"
              >
                <el-option
                  v-for="item in taxRateCodeList"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="含税总金额"
            :min-width="SETTINGS.settings_decimalDigits_length"
            prop="totalTaxPrice"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.totalTaxPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购交期" fixed="right" width="140" prop="purchaseDeliveryTime">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.purchaseDeliveryTime"
                :disabled="scope.row.status == '3'"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                :disabled="scope.row.status == '3'"
                placeholder="请输入"
                clearable
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo,
  supplierList
} from "@/api/purchaseManage/purchaseOrder";
import addOrderForm from "./addOrderForm";
import supplier from "./supplier";
import moment from "moment";
import { getDictSelects } from "@/api/common/common";
import Big from "big.js"; // big.js解决精度丢失问题
export default {
  name: "AddOrUpdate",
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        model: undefined,
        requisitionData: undefined,
        fileName: "",
        fileRealName: "",
        url: "",
        remark: undefined,
        supplierName: undefined,
        isTaxTotalMoney: false,
        totalNumber: "",
        taxTotalMoney: "",
        purchaseOrder: "",
        orderTime: "",
        status: 1,
        detailList: []
      },
      detailedData: [],
      requisitionDataOne: [],
      tableHeight: "",
      selectionsAll1: [],
      taxRateCodeList: [],
      ids: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      totalTaxPriceNumOne: "",
      tableDate: [],
      listData: [],
      copyData: [],
      rules: {
        code: [
          { required: true, message: "采购订单不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "change" }
        ]
      },
      orderDate: {
        supplierId: "",
        materialIds: []
      },
      materialIdsOne: "",
      triggerTag: false // 含税总金额/合计触发条件
    };
  },
  watch: {
    listData() {
      if (this.listData.length > 7) {
        this.tableHeight = "390";
      } else {
        this.tableHeight = "";
      }
      console.log(this.listData);
      this.$refs["table"].doLayout();
    }
  },
  created() {
    if (!this.id) {
      // 没有id就是新增
    } else {
      // 有id就是编辑
      this.getInfo();
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  mounted() {
    this.formData.orderName = this.$store.state.user.name;
    this.formData.orderBy = this.$store.state.user.userId;
    this.formData.orderTime = moment(new Date()).format("YYYY-MM-DD");
    this.getDictOptions();
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, "fileName", data[0]);
      this.$set(this.formData, "fileRealName", data[1]);
      this.$set(this.formData, "url", data[2]);
    },
    tableSelectable(row, index) {
      if (row.status == "3") {
        return false;
      } else {
        return true;
      }
    },
    headerCellClassName(data) {
      if (["purchaseNumber"].indexOf(data.column.property) != -1) {
        return "column_bt";
      }
      if (["purchaseDeliveryTime"].indexOf(data.column.property) != -1) {
        return "column_bt";
      }
    },
    getDictOptions() {
      getDictSelects("taxRateCode").then(res => {
        this.taxRateCodeList = res.data;
      });
    },
    changeTaxRateCode(e, row, index) {
      this.taxRateCodeList.forEach(ele => {
        if (ele.dictCode == e) {
          this.listData[index].taxRateLabel = ele.dictLabel;
          this.listData[index].taxRateCode = ele.dictCode;
        }
      });
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows;
    },
    // 合计行
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = "合计";
          return;
        }
        switch (column.property) {
          case "purchaseNumber":
            sums[index] = data
              .map(item => item.purchaseNumber)
              .reduce((prev, curr) => {
                if (curr) {
                  return new Big(prev).plus(curr).toString();
                } else {
                  return new Big(prev).toString();
                }
              }, 0);
            this.formData.totalNumber = sums[index];
            break;
        }
        switch (column.property) {
          case "totalTaxPrice":
            sums[index] = data
              .map(item => item.totalTaxPrice)
              .reduce((prev, curr) => {
                if (curr) {
                  return new Big(prev).plus(curr).toString();
                } else {
                  return new Big(prev).toString();
                }
              }, 0);
            if (this.triggerTag) {
              this.formData.taxTotalMoney = sums[index];
            }

            break;
        }
      });
      return sums;
    },
    changeTaxPrice(e, row, index) {
      this.triggerTag = true;
      if (row.taxPrice) {
        const totalTaxPriceData = this.$deepClone(this.listData);
        for (var i = 0; i < totalTaxPriceData.length; i++) {
          if (totalTaxPriceData[i].materialId === row.materialId) {
            totalTaxPriceData[i].totalTaxPrice = new Big(
              totalTaxPriceData[i].taxPrice
            )
              .times(totalTaxPriceData[i].purchaseNumber)
              .toString();
          }
        }
        this.listData = totalTaxPriceData;
      } else {
        this.listData[index].totalTaxPrice = 0;
      }
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data;
        this.listData = res.data.detailList;
        this.listData.forEach(item => {
          item.dictLabel = item.taxRateLabel;
          item.taxRateCode = item.taxRateCode;
          if (item.taxPrice == "" || item.taxPrice == null) {
            item.taxPrice = "0";
            item.totalTaxPrice = "";
            item.taxRateLabel = "";
            item.taxRateCode = "";
          }
        });
      });
    },
    remove1() {
      const requisitionDataOne = JSON.parse(this.formData.requisitionData);
      const add = requisitionDataOne.filter(
        item =>
          !this.selectionsAll1.some(ele => ele.materialId == item.materialId)
      );
      this.formData.requisitionData = JSON.stringify(add);
      this.selectionsAll1.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1);
        requisitionDataOne.splice(
          requisitionDataOne.indexOf(item.materialId),
          1
        );
      });
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: addOrderForm, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.formData.requisitionData
              ? JSON.parse(this.formData.requisitionData)
              : "",
            copyData: this.listData ? this.listData : ""
          } // props
        },
        area: ["1320px", "700px"],
        title: "选择物料", // 标题
        shadeClose: false // 点击遮罩是否关闭
      });
    },
    // 选择供应商
    choosePeople() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: supplier, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.listData,
            id: this.formData.supplierId ? this.formData.supplierId : ""
          } // props
        },
        area: ["880px", "700px"],
        title: "选择供应商", // 标题
        shadeClose: false // 点击遮罩是否关闭
      });
    },
    onSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.listData && this.listData.filter(item => item).length <= 0) {
            this.$message.warning("请添加采购订单明细");
            return;
          } else if (
            this.listData.filter(
              item =>
                item.taxPrice && !this.SETTINGS.reg_zero.test(item.taxPrice)
            ).length > 0
          ) {
            this.$message.warning("含税单价未正确填写");
            return;
          }
          if (this.formData.supplierId == undefined) {
            this.formData.supplierId = this.orderDate.supplierId;
          }
          if (
            this.listData.filter(item => !item.purchaseDeliveryTime).length > 0
          ) {
            this.$message.warning("采购交期不能为空");
            return;
          }
          if (
            this.listData.filter(
              item => item.purchaseDeliveryTime >= this.formData.orderTime
            ).length == 0
          ) {
            this.$message.warning("采购交期不得小于采购日期");
            return;
          }
          this.formData.status = 1;
          this.listData.forEach(item => {
            item.id = "";
            delete item.id;
          });

          this.formData.detailList = this.listData;
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.$layer.close(this.layerid); // 关闭弹框
            this.$parent.getList();
          });
        }
      });
    },
    cancel() {
      this.$layer.close(this.layerid); // 关闭弹框
    },
    // 获取供应商下面的订单价格
    getSupplierList() {
      supplierList(this.orderDate).then(res => {
        const cacheListData = this.$deepClone(this.listData);
        // if (res.data.length == 0) {
        //   cacheListData.forEach(item1 => {
        //     item1.taxPrice = ''
        //     item1.totalTaxPrice = ''
        //     item1.taxRateLabel = ''
        //     item1.taxRateCode = ''
        //   })
        // }
        res.data.forEach(item => {
          cacheListData.forEach(item2 => {
            if (item2.materialId == item.materialId) {
              item2.taxPrice = item.taxPrice;
              item2.taxRateCode = item.taxRateCode;
              item2.taxRateLabel = item.taxRateLabel;
              item2.totalTaxPrice = new Big(item2.taxPrice)
                .times(item2.purchaseNumber)
                .toString();
            }
          });
        });
        this.listData = cacheListData;
      });
    },
    // 选择供应商的回调
    chooseCustomer(data) {
      let materialIds1 = [];
      if (!this.formData.supplierName) {
        this.orderDate.supplierId = data.id;
        this.formData.supplierName = data.name;
        this.formData.supplierId = data.id;
      } else {
        this.orderDate.supplierId = data.id;
        this.formData.supplierName = data.name;
        this.formData.supplierId = data.id;
        this.listData.forEach(item => {
          materialIds1.push(item.materialId);
          item.taxPrice = "";
          item.totalTaxPrice = "";
          item.taxRateLabel = "";
          item.taxRateCode = "";
          item.purchaseDeliveryTime = "";
          item.remark = "";
        });
      }
      this.orderDate.materialIds = materialIds1;
      if (
        this.orderDate.supplierId !== "" &&
        this.orderDate.materialIds.length > 0
      ) {
        this.getSupplierList();
      }
    },
    // 选择订单明细的回调
    showMaterial(data, row) {
      this.detailedData = this.$deepClone(data); // 合并前的每一条数据
      let allArrOne = [];
      this.formData.requisitionData = JSON.stringify(this.$deepClone(data));
      allArrOne = this.$deepClone(data);
      let number = 0;
      allArrOne.forEach(item => {
        number = 0;
        const ids = [];
        if (
          data.filter(item2 => item.materialId == item2.materialId).length > 0
        ) {
          data
            .filter(item2 => item.materialId == item2.materialId)
            .forEach(item3 => {
              number = number + Number(item3.purchase);
              ids.push(item3.purchaseRequisitionDetailIds);
            });
          item.purchaseNumber = number;
          item.purchaseRequisitionDetailIds = ids.join(",");
        }
        delete item["id"];
        item.remark = "";
      });
      // 去重
      const allArr = [];
      for (var i = 0; i < allArrOne.length; i++) {
        let flag = true;
        for (var j = 0; j < allArr.length; j++) {
          if (allArrOne[i].materialId == allArr[j].materialId) {
            flag = false;
          }
        }
        if (flag) {
          allArr.push(allArrOne[i]);
        }
      }
      // 获取每条物料id
      this.listData = allArr;
      const materialIds1 = [];
      this.listData.forEach(item => {
        materialIds1.push(item.materialId);
        row.forEach(ele => {
          if (
            ele.purchaseRequisitionDetailIds ==
            item.purchaseRequisitionDetailIds
          ) {
            item.taxPrice = ele.taxPrice;
            item.taxRateLabel = ele.taxRateLabel;
            item.totalTaxPrice = ele.totalTaxPrice;
            item.taxRateCode = ele.taxRateCode;
            item.remark = ele.remark;
            item.purchaseDeliveryTime = ele.purchaseDeliveryTime;
            item.status = ele.status;
          }
        });
      });
      this.orderDate.materialIds = materialIds1;
      this.orderDate.supplierId = this.formData.supplierId;
      this.formData.isTaxTotalMoney = true;
      // 获取供应商下价格
      if (
        this.orderDate.supplierId !== undefined &&
        this.orderDate.materialIds.length > 0
      ) {
        this.getSupplierList();
      }
      this.triggerTag = true; // 2024/1/17 葛确认添加物料后合计的含税总金额要带到上面去
    }
  }
};
</script>

<style lang="less" scoped>
.table_container {
  padding-bottom: 20px;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
</style>
